package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

@Service

public class ShoppingCartSericeImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {
        ShoppingCart dbShoppingCart = shoppingCartMapper.findByShoppingCart(shoppingCart);
        if (dbShoppingCart!= null) {
            //如果不为空就加1 调用,mapper跟新数量
            dbShoppingCart.setNumber(dbShoppingCart.getNumber()+1);
            shoppingCartMapper.updateNumber(dbShoppingCart.getId(),dbShoppingCart.getNumber());
            //如果没有就添加一个 新的
        }else {
            //完善时间 完善数量
            dbShoppingCart=shoppingCart;
            dbShoppingCart.setCreateTime(LocalDateTime.now());
            dbShoppingCart.setNumber(1);
            //最后插入
           shoppingCartMapper.save(dbShoppingCart);

        }
        return dbShoppingCart;
    }


    @Override
    public List<ShoppingCart> findAllByUserId(Long userId) {

        return shoppingCartMapper.findAllByUserId(userId);

    }

    @Override
    public void clean(Long userId) {
        shoppingCartMapper.deleteByUserId(userId);
    }
}
